package com.zzyl.config;

import com.zzyl.properties.MinioConfigProperties;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Slf4j
@ConditionalOnClass(MinioConfigProperties.class)
@EnableConfigurationProperties(MinioConfigProperties.class)
@Configuration
public class MinioAutoConfig {

    @Autowired
    private MinioConfigProperties minioConfigProperties;

    @Bean
    public MinioClient minioClient() throws Exception {
        log.info("-----------------开始创建MinioClient--------------------");
        
        // 创建MinioClient实例
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioConfigProperties.getEndpoint())
                .credentials(
                    minioConfigProperties.getAccessKey(), 
                    minioConfigProperties.getSecretKey()
                )
                .build();

        // 检查桶是否存在，不存在则创建
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder()
                .bucket(minioConfigProperties.getBucketName())
                .build();

        boolean isExist = minioClient.bucketExists(bucketExistsArgs);
        if (!isExist) {
            MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder()
                    .bucket(minioConfigProperties.getBucketName())
                    .build();
            minioClient.makeBucket(makeBucketArgs);
            
            // 设置桶策略为公开读
            String policy = "{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":\"*\",\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::" + minioConfigProperties.getBucketName() + "/*\"]}]}";
            SetBucketPolicyArgs setPolicyArgs = SetBucketPolicyArgs.builder()
                    .bucket(minioConfigProperties.getBucketName())
                    .config(policy)
                    .build();
            minioClient.setBucketPolicy(setPolicyArgs);
        }

        log.info("-----------------MinioClient创建成功--------------------");
        return minioClient;
    }
}